package com.btpn.custody.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.btpn.custody.dao.IUser;
import com.btpn.custody.entity.User;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Service("userDaoHibernate")
@Transactional
public class UserDAO implements IUser {

	protected HibernateTemplate template = null;
	
//	private SessionFactory sessionFactory;

	@Autowired @Required
	public void setSessionFactory(SessionFactory sessionFactory) {
//		this.sessionFactory = sessionFactory;
		template = new HibernateTemplate(sessionFactory);
	}

//	@Override
//	@Transactional(readOnly=true)
//	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//		User user = (User) sessionFactory.getCurrentSession().get(User.class, username);
//		if (user == null) {
//			throw new UsernameNotFoundException("Could not find a user named: " + username);
//		}
//		return user;
//	}

	@Override
	@Transactional(readOnly=true)
	public User get(String username) {
		return template.get(User.class, username);
	}

	@Override
	@Transactional(readOnly=true)
	public List<User> findAll() {
		return template.loadAll(User.class);
	}

	@Override
	@Transactional(readOnly=true)
	public Integer getCount() {
		return Integer.valueOf(findAll().size());
	}
	
	@Override
	public Serializable create(User user) {
		return template.save(user);
	}

	@Override
	public void createOrUpdate(User user) {
		template.saveOrUpdate(user);
	}
	
	@Override
	public void update(User user) {
		template.update(user);
	}

	@Override
	public void delete(User user) {
		template.delete(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findByGroupRole(Long groupRoleId) {
		return template.findByNamedQueryAndNamedParam(User.NQ__FIND__BY__GROUPROLE_ID, new String[] {"groupRoleId"}, new Object[] {groupRoleId});
	}

//	@SuppressWarnings("unchecked")
//	@Override
//	public List<User> findByAreaId(Long areaId) {
//		return template.findByNamedQueryAndNamedParam(User.NQ__FIND__BY__AREA_ID, new String[] {"areaId"}, new Object[] {areaId});
//	}
}